<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="律师姓名" prop="lawyerName">
        <el-input
          v-model="queryParams.lawyerName"
          placeholder="请输入律师姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属律所名称" prop="lawFirmName">
        <el-input
          v-model="queryParams.lawFirmName"
          placeholder="请输入所属律所名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在线状态" prop="onlineStatus">
        <el-select
          v-model="queryParams.onlineStatus"
          placeholder="请选择在线状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.online_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:lawyer:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:lawyer:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:lawyer:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:lawyer:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleSyncLawyerToEs"
          >同步到ES</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="lawyerList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="律师ID，主键" align="center" prop="lawyerId" />
      <el-table-column label="关联用户ID" align="center" prop="userId" />
      <el-table-column label="律师姓名" align="center" prop="lawyerName" />
      <el-table-column label="所属律所名称" align="center" prop="lawFirmName" />
      <el-table-column label="职称/头衔" align="center" prop="title" />
      <el-table-column label="律师简介" align="center" prop="introduction">
        <template slot-scope="scope">
          <div class="ellipsis" @click="handleView(scope.row)">
            <!--            {{ scope.row.newsContent | truncate(5) }} &lt;!&ndash; 显示前5个字 &ndash;&gt;-->
            {{ scope.row.introduction.slice(0, 3) + "..." }}
            <!-- 显示前3字 -->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" align="center" prop="onlineStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.online_status"
            :value="scope.row.onlineStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="咨询价格"
        align="center"
        prop="consultationPrice"
      />
      <el-table-column label="平均评分" align="center" prop="averageRating" />
      <el-table-column label="律师执业证号" align="center" prop="licenseNo" />
      <el-table-column label="执业年限" align="center" prop="practiceYears" />
      <el-table-column label="专业领域" align="center" prop="expertise">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.expertise"
            :value="scope.row.expertise ? scope.row.expertise.split(',') : []"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="lawyerStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.lawyer_status"
            :value="scope.row.lawyerStatus"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:lawyer:edit']"
            >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:lawyer:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 律师详情对话框 -->
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewOpen"
      width="800px"
      append-to-body
      class="lawyer-detail-dialog"
    >
      <div class="lawyer-detail">
        <!-- 头像与基础信息区域 -->
        <div
          class="header-container"
          style="
            display: flex;
            align-items: center;
            gap: 30px;
            margin-bottom: 30px;
          "
        >
          <div class="avatar-wrapper">
            <!-- 头像容器增加圆角与阴影效果 -->
            <img
              :src="viewForm.avatar"
              alt="律师头像"
              class="lawyer-avatar"
              style="
                width: 120px;
                height: 120px;
                border-radius: 10px;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              "
            />
          </div>

          <div class="basic-info">
            <!-- 姓名增加视觉层级 -->
            <h2 style="font-size: 20px; margin-bottom: 8px; color: #333">
              {{ viewForm.lawyerName }}
            </h2>

            <div class="user-info" style="color: #666; font-size: 14px">
              <span style="margin-right: 20px"
                >用户名：{{ viewForm.userName }}</span
              >
              <!-- 保留性别标签，移除图标 -->
              <span>
                <dict-tag
                  :options="dict.type.gender"
                  :value="viewForm.gender"
                />
              </span>
            </div>
          </div>
        </div>

        <!-- 联系方式模块 -->
        <div class="detail-section contact-section" style="margin-bottom: 25px">
          <h3 style="font-size: 16px; color: #333; margin-bottom: 15px">
            联系方式
          </h3>

          <div
            class="contact-info"
            style="color: #666; font-size: 14px; line-height: 2.2"
          >
            <!-- 移除电话图标 -->
            <span style="display: flex; align-items: center">
              {{ viewForm.phoneNumber || "未提供" }}
            </span>

            <!-- 移除地址图标 -->
            <span style="display: flex; align-items: center; margin-left: 30px">
              {{ viewForm.contactAddress || "未提供" }}
            </span>
          </div>
        </div>

        <!-- 执业信息模块 -->
        <div class="detail-section" style="margin-bottom: 25px">
          <h3 style="font-size: 16px; color: #333; margin-bottom: 15px">
            执业信息
          </h3>

          <div
            class="meta-info"
            style="color: #666; font-size: 14px; display: flex; gap: 30px"
          >
            <span>所属律所：{{ viewForm.lawFirmName }}</span>
            <span>执业年限：{{ viewForm.practiceYears }}年</span>
            <span>咨询价格：{{ viewForm.consultationPrice }}元/次</span>
          </div>
        </div>

        <!-- 专业领域模块（优化标签样式） -->
        <div
          class="detail-section"
          v-if="viewForm.expertise"
          style="margin-bottom: 25px"
        >
          <h3 style="font-size: 16px; color: #333; margin-bottom: 15px">
            专业领域
          </h3>

          <div
            class="tag-list"
            style="display: flex; flex-wrap: wrap; gap: 8px"
          >
            <dict-tag
              v-for="(tag, index) in viewForm.expertise.split(',')"
              :key="index"
              :options="dict.type.expertise"
              :value="tag"
              class="tag"
              style="
                background-color: #f5f7fa;
                color: #666;
                padding: 4px 12px;
                border-radius: 20px;
                font-size: 12px;
              "
            />
          </div>
        </div>

        <!-- 律师简介模块（增加边框与内边距） -->
        <div
          class="detail-section"
          style="
            margin-bottom: 25px;
            border: 1px solid #f0f2f5;
            border-radius: 6px;
            padding: 18px;
          "
        >
          <h3 style="font-size: 16px; color: #333; margin-bottom: 15px">
            律师简介
          </h3>

          <div
            v-html="viewForm.introduction"
            class="content"
            style="color: #666; line-height: 1.8; font-size: 14px"
          ></div>
        </div>

        <!-- 状态信息模块（分行展示） -->
        <div class="detail-section">
          <h3 style="font-size: 16px; color: #333; margin-bottom: 15px">
            账户状态
          </h3>

          <div class="status-info" style="color: #666; font-size: 14px">
            <div
              class="status-item"
              style="margin-bottom: 8px; display: flex; align-items: center"
            >
              <span style="margin-right: 12px">在线状态：</span>
              <dict-tag
                :options="dict.type.online_status"
                :value="viewForm.onlineStatus"
              />
            </div>

            <div class="status-item" style="display: flex; align-items: center">
              <span style="margin-right: 12px">审核状态：</span>
              <dict-tag
                :options="dict.type.lawyer_status"
                :value="viewForm.lawyerStatus"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮优化（增加间距与视觉反馈） -->
      <div
        slot="footer"
        class="dialog-footer"
        style="
          display: flex;
          justify-content: flex-end;
          padding: 20px;
          border-top: 1px solid #f0f2f5;
        "
      >
        <el-button
          type="primary"
          @click="lawyerDetailClose"
          style="padding: 8px 24px; font-weight: 500"
        >
          关闭
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改律师信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入关联用户ID" />
        </el-form-item>
        <el-form-item label="律师姓名" prop="lawyerName">
          <el-input v-model="form.lawyerName" placeholder="请输入律师姓名" />
        </el-form-item>
        <el-form-item label="所属律所名称" prop="lawFirmName">
          <el-input
            v-model="form.lawFirmName"
            placeholder="请输入所属律所名称"
          />
        </el-form-item>
        <el-form-item label="职称/头衔" prop="title">
          <el-input v-model="form.title" placeholder="请输入职称/头衔" />
        </el-form-item>
        <el-form-item label="律师简介" prop="introduction">
          <el-input
            v-model="form.introduction"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="咨询价格" prop="consultationPrice">
          <el-input
            v-model="form.consultationPrice"
            placeholder="请输入咨询价格"
          />
        </el-form-item>
        <el-form-item label="律师执业证号" prop="licenseNo">
          <el-input v-model="form.licenseNo" placeholder="请输入律师执业证号" />
        </el-form-item>
        <el-form-item label="执业年限" prop="practiceYears">
          <el-input v-model="form.practiceYears" placeholder="请输入执业年限" />
        </el-form-item>
        <el-form-item label="专业领域" prop="expertise">
          <el-checkbox-group v-model="form.expertise">
            <el-checkbox
              v-for="dict in dict.type.expertise"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="申请状态" prop="lawyerStatus">
          <el-radio-group v-model="form.lawyerStatus">
            <el-radio
              v-for="dict in dict.type.lawyer_status"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLawyer,
  getLawyer,
  getLawyerDetails,
  delLawyer,
  addLawyer,
  updateLawyer,
  updateLawyerToEs,
} from "@/api/lawyer_aid/lawyer";

export default {
  name: "Lawyer",
  dicts: [
    "online_status",
    "lawyer_status",
    "is_deleted",
    "expertise",
    "gender",
  ],
  data() {
    return {
      // 新增详情对话框数据
      viewOpen: false,
      viewTitle: "律师介绍",
      viewForm: {},

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 律师信息表格数据
      lawyerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        lawyerName: null,
        lawFirmName: null,
        onlineStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "关联用户ID不能为空", trigger: "blur" },
        ],
        lawyerName: [
          { required: true, message: "律师姓名不能为空", trigger: "blur" },
        ],
        lawFirmName: [
          { required: true, message: "所属律所名称不能为空", trigger: "blur" },
        ],
        title: [
          { required: true, message: "职称/头衔不能为空", trigger: "blur" },
        ],
        introduction: [
          { required: true, message: "律师简介不能为空", trigger: "blur" },
        ],
        consultationPrice: [
          { required: true, message: "咨询价格不能为空", trigger: "blur" },
        ],
        licenseNo: [
          { required: true, message: "律师执业证号不能为空", trigger: "blur" },
        ],
        practiceYears: [
          { required: true, message: "执业年限不能为空", trigger: "blur" },
        ],
        expertise: [
          { required: true, message: "专业领域不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询律师信息列表 */
    getList() {
      this.loading = true;
      listLawyer(this.queryParams).then((response) => {
        this.lawyerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 查看详情方法（优化后通过接口获取数据）
    handleView(row) {
      const lawyerId = row.lawyerId;
      this.viewOpen = true;
      this.loading = true; // 显示加载状态

      // 调用详情接口
      getLawyerDetails(lawyerId)
        .then((response) => {
          this.viewForm = response.data; // 赋值详情数据
          this.loading = false; // 隐藏加载状态
        })
        .catch((error) => {
          this.$modal.msgError("获取详情失败");
          this.viewOpen = false;
        });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 关闭详情弹窗
    lawyerDetailClose() {
      this.viewOpen = false;
      this.lawyerDetailsReset();
    },

    lawyerDetailsReset() {
      this.viewForm = {
        lawyerId: null,
        userId: null,
        lawyerName: null,
        lawFirmName: null,
        title: null,
        introduction: null,
        onlineStatus: null,
        consultationPrice: null,
        averageRating: null,
        licenseNo: null,
        practiceYears: null,
        // 初始值，设为空字符串  不能设为[]
        expertise: "",
        lawyerStatus: null,
        isDeleted: null,
        createdTime: null,
        createdBy: null,
        updatedBy: null,
        updateTime: null,
      };
      this.reset("viewForm");
    },
    // 表单重置
    reset() {
      this.form = {
        lawyerId: null,
        userId: null,
        lawyerName: null,
        lawFirmName: null,
        title: null,
        introduction: null,
        onlineStatus: null,
        consultationPrice: null,
        averageRating: null,
        licenseNo: null,
        practiceYears: null,
        expertise: [],
        lawyerStatus: null,
        isDeleted: null,
        createdTime: null,
        createdBy: null,
        updatedBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.lawyerId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加律师信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lawyerId = row.lawyerId || this.ids;
      getLawyer(lawyerId).then((response) => {
        this.form = response.data;
        this.form.expertise = this.form.expertise.split(",");
        this.open = true;
        this.title = "修改律师信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.expertise = this.form.expertise.join(",");
          if (this.form.lawyerId != null) {
            updateLawyer(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLawyer(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lawyerIds = row.lawyerId || this.ids;
      this.$modal
        .confirm('是否确认删除律师信息编号为"' + lawyerIds + '"的数据项？')
        .then(function () {
          return delLawyer(lawyerIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/lawyer/export",
        {
          ...this.queryParams,
        },
        `lawyer_${new Date().getTime()}.xlsx`
      );
    },
    handleSyncLawyerToEs() {
      this.$modal.confirm("确定要将所有律师信息同步到ES吗？").then(() => {
        this.loading = true;
        updateLawyerToEs()
          .then((res) => {
            this.loading = false;
            if (res.code === 200) {
              this.$modal.msgSuccess("同步成功");
            } else {
              this.$modal.msgError(res.msg || "同步失败");
            }
          })
          .catch(() => {
            this.loading = false;
            this.$modal.msgError("同步失败");
          });
      });
    },
  },
};
</script>

<style scoped>
/* 自定义对话框样式 */
.lawyer-detail-dialog {
  border-radius: 10px;
}

/* 头像和基础信息栏 */
.header-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-wrapper {
  margin-right: 20px;
}

.lawyer-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 2px solid #ddd;
}

.basic-info h2 {
  margin: 0 0 10px;
  font-size: 24px;
}

.user-info span {
  display: block;
  margin-bottom: 5px;
}

/* 联系方式和执业信息 */
.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  margin: 0 0 10px;
  font-size: 18px;
  color: #333;
}

.contact-info span,
.meta-info span {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
}

/* 专业领域 */
.tag-list {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 5px 10px;
  background-color: #f0f2f5;
  border-radius: 5px;
  font-size: 14px;
}

/* 律师简介 */
.content {
  white-space: pre-line;
  font-size: 14px;
  color: #666;
}

/* 状态信息 */
.status-info {
  display: flex;
  flex-direction: column;
}

.status-item {
  margin-bottom: 10px;
  font-size: 14px;
}

/* 对话框底部按钮 */
.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
</style>
